/* eslint-disable default-case */
/* eslint-disable consistent-return */
import { message } from 'antd';
import _ from 'lodash';
import {
  getEmpList,
  probEmpList,
  empTabNum,
  getUploadProgress,
  getProDetail,
  getFeedback,
  getQuerycity,
  getEmpSeleInfo,
  platformSupplier,
  contractpartyList,
  custrnameList,
  getBusinessList,
  getQuotationList,
  gethetionList,
  getCustmorList,
  pleaseListqun,
  costCenterList,
  personnelStatusList,
  getPartyList,
  agreeWithone,
  providentRatioList,
  providentFundList,
  accountPolicy,
  serviceConfiguraList,
  laborContract,
  isStafffaction,
  addAlert,
  upTipsalert,
  subMessage,
  dictionariesList,
  batchCancelAddemp,
  getPdInfoList,
  uploadFileAddEmp,
  getRespUserList,
} from '@/services/customerservicemanage';
import * as service from '@/services/socket';
import { SocketActions, batchTaskFactory } from '@/models/socket';
import { delay } from '@/utils/dva';
// 非常重要属性
const namespace = 'addemp';
const ModelAddEmp = {
  namespace,
  state: {
    activeKey: '1',
    tabList: [
      { itemCode: '1', itemName: '办理中', isHasBadge: false },
      { itemCode: '2', itemName: '已完成', isHasBadge: false },
      { itemCode: '4', itemName: '问题人员', isHasBadge: false },
      { itemCode: '3', itemName: '已取消', isHasBadge: false },
    ],
    formFieldsValue: {},
    valuesArr: [
      'empName',
      'idCode',
      'sendType',
      'custId',
      'quoId',
      'custContId',
      'operTime',
      'taskSource',
      'cityId',
      'primId',
    ],
    expandForm: false,
    pageData: {
      // 列表数据
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    batchQuery: {
      // 批量上传数据
      sendType: '1', // 服务类型
      isSerSetFlag: '2', // 使用服务配置
      tempFlag: '1', // 五险是否一致
      advancedSetFlag: '2', // 是否高级设置
      pdIds: ['PDINF_0000000001', 'PDINF_0000000002'], // 模板适用产品
      citySplitFlag: '1', // 产品执行地
      dateSplitFlag: '2', // 产品开始日期
      progressPercent: 0,
    },
    dictionList: {},
    proBaseList: {},
    proFbList: [],
    probId: '',
    addempQuery: {
      suppId: undefined, // 签约方id
      custId: undefined, // 客户名称id
      contId: undefined, // 商务合同id
      quoId: undefined, // 报价单id
    },
    isSameComy: true,
    suppReplaceCorpId: '', // 当前角色所在公司id
    supplyList: [], // 签约方
    customerNameList: [], // 签约方为本地，客户名称
    contList: [], // 商务合同列表
    quoList: [], // 报价单列表
    supplyContList: [], // 供应商合同列表
    showProgress: false,
    currentStep: 0,
    progressPercent: 0,
    resultInfo: {
      // 结果数据必传
      batchName: '批量增员任务', // 任务名称
      taskCount: 0, // 导入数据
      successCount: 0, // 成功数据
      errorCount: 0, // 失败数据
      batchNo: '', // 批次号
      errorUrl: '/csApi/empSendCreateService/exportErrorExcel', // 下载错误信息地址
      errorParams: null, // 下载错误数据参数
    },
    productList: [], // 模板适用产品
    respUserList: [],
    downloadParams: {}, // 问题人员导出参数
  },

  effects: {
    // 获取列表
    fetchList: [
      function*({ payload }, { call, put }) {
        const response = yield call(getEmpList, payload);
        const {
          pageArg: { currentPage, pageSize },
        } = payload;
        yield put({
          type: 'updateList',
          payload: {
            data: {},
            currentPage,
            pageSize,
          },
        });
        if (response.success) {
          yield put({
            type: 'updateList',
            payload: {
              data: response.data,
              currentPage,
              pageSize,
            },
          });
        } else {
          message.warning(`${response.message || '服务端错误！'}`);
        }
      },
      { type: 'takeLatest' },
    ],
    // 获取问题人员列表
    *fetchProbList({ payload }, { call, put }) {
      const response = yield call(probEmpList, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      yield put({
        type: 'updateList',
        payload: {
          data: {},
          currentPage,
          pageSize,
        },
      });
      if (response.success) {
        yield put({
          type: 'updateList',
          payload: {
            data: response.data,
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(`${response.message || '服务端错误！'}`);
      }
    },
    /**
     * 获取页签数量
     * @param {action} action
     * @param {effects} effects
     * @return {response} response
     */
    *fetchTabNum({ payload }, { call }) {
      const response = yield call(empTabNum, payload.formFieldsValue);
      return response;
    },
    /**
     * 设置激活页签
     * @param {action} action
     * @param {effects} effects
     * @return {string} activeKey
     */
    *setFetchTabNumActiveKey({ payload }, { put, select }) {
      let activeKey = yield select(state => state.addemp.activeKey);
      const newTabList = yield select(state => state.addemp.tabList);
      const tabList = _.cloneDeep(newTabList);
      const { data } = payload;
      // 按itemCode大小排序
      const sortNumber = (a, b) => a.itemCode - b.itemCode;
      // 排序后的tabCode数组
      const tabCodeArr = data.sort(sortNumber);
      // 在tabCodeArr中找到当前的激活项
      const isHasBadgeCurrentTab = tabCodeArr.some(item => `${item.status}` === activeKey); // 当前页签有没有查询到
      // 没有找到就把第0项设为当前的激活项
      if (!isHasBadgeCurrentTab) {
        activeKey = `${tabCodeArr[0].status}`;
      }
      tabCodeArr.forEach(item => {
        tabList.forEach((tab, index) => {
          if (`${item.status}` === activeKey && `${item.status}` === tab.itemCode) {
            tabList[index].isHasBadge = false;
          } else if (`${item.status}` !== activeKey && `${item.status}` === tab.itemCode) {
            tabList[index].isHasBadge = true;
          }
        });
      });
      yield put({
        type: 'updateModelData',
        payload: { activeKey, tabList },
      });
      return activeKey;
    },
    *setFetchTabNumFormFieldsValue({ payload }, { put, select }) {
      const activeKey = yield select(state => state.addemp.activeKey);
      const getListParams = {
        ...payload.formFieldsValue,
        pageArg: { currentPage: payload.currentPage, pageSize: payload.pageSize },
      };
      if (activeKey === '4') {
        if (payload.formFieldsValue) {
          yield put({
            type: 'updateModelData',
            payload: {
              ...payload.formFieldsValue,
            },
          });
        }
        yield put({
          type: 'problempage/getProList',
          payload: {
            ...getListParams,
            busiType: 20,
          },
        });
      } else {
        yield put({
          type: 'fetchList',
          payload: { ...getListParams, taskStatus: activeKey },
        });
      }
    },
    *setFetchTabNumNoResult(action, { put, select }) {
      const activeKey = yield select(state => state.addemp.activeKey);
      yield put({
        type: 'updateList',
        payload: {
          data: {},
          currentPage: 1,
          pageSize: 10,
        },
      });
      if (activeKey === '4') {
        yield put({
          type: 'problempage/updateProList',
          payload: {
            data: [],
            currentPage: 1,
            pageSize: 10,
          },
        });
      }
    },
    // 获取上传进度数据
    *getUploadProgress({ payload, callback }, { call, put }) {
      const response = yield call(getUploadProgress, payload);
      if (response.success) {
        yield put({
          type: 'updateQuery',
          payload: { progressPercent: response.data.successProp },
        });
      }
      if (callback && typeof callback === 'function') {
        callback(response);
      }
    },

    // 批量取消增员任务：获取进度数据
    *getProgress({ payload }, { call, put }) {
      const response = yield call(getUploadProgress, payload);
      if (response.success && response.data) {
        yield put({
          type: 'updateModelData',
          payload: { progressPercent: response.data.successProp },
        });
      }
      return response;
    },

    // 获取问题人员详情
    *fetchProDetailList({ payload }, { call, put }) {
      const response = yield call(getProDetail, payload);
      if (response.success) {
        yield put({
          type: 'getProDetail',
          payload: response.data,
        });
      }
    },
    // 问题人员反馈
    *proFeedBack({ payload, callback }, { call }) {
      const response = yield call(getFeedback, payload);
      if (response.success) {
        if (callback) {
          callback(response);
        }
      } else {
        message.warning(`${response.message || '反馈失败'}`);
      }
    },
    // 问题人员反馈并取消标记
    *cancelProbFlag({ payload, callback }, { call }) {
      const response = yield call(getFeedback, payload);
      if (callback) {
        callback(response);
      }
    },

    // *************************************************************************** ylq
    // 查询市
    *querycity({ payload, callback }, { call }) {
      const response = yield call(getQuerycity, payload);
      if (callback) {
        callback(response);
      }
    },
    // 获取当前角色所在公司对应的平台供应商
    *plasuppList({ payload, callback }, { call }) {
      const response = yield call(platformSupplier, payload);
      if (callback) {
        callback(response);
      }
    },

    // 签约方列表
    *contractParty({ payload, callback }, { call }) {
      const response = yield call(contractpartyList, payload);
      if (callback) {
        callback(response);
      }
    },

    // 客户名称列表
    *customerList({ payload, callback }, { call }) {
      const response = yield call(custrnameList, payload);
      if (callback) {
        callback(response);
      }
    },
    // 获取字典
    *fetchDictCode({ payload, callback }, { call }) {
      const response = yield call(dictionariesList, payload);
      if (response.success) {
        if (callback) {
          callback(response.data);
        }
      }
    },

    // 选择客户名称：请求商务合同
    *getBusiness({ payload, callback }, { call }) {
      const response = yield call(getBusinessList, payload);
      if (callback) {
        callback(response);
      }
    },

    // 选择商务合同：请求报价单
    *getQuotation({ payload, callback }, { call }) {
      const response = yield call(getQuotationList, payload);
      if (callback) {
        callback(response);
      }
    },

    // 根据签约方为全国：请求供应商合同
    *getNameList({ payload, callback }, { call }) {
      const response = yield call(gethetionList, payload);
      if (callback) {
        callback(response);
      }
    },

    // 根据选择的供应商合同：请求客户名称
    *getCustnameList({ payload, callback }, { call }) {
      const response = yield call(getCustmorList, payload);
      if (callback) {
        callback(response);
      }
    },

    *subaddMessage({ payload, callback }, { call }) {
      const response = yield call(subMessage, payload);
      if (callback) {
        callback(response);
      }
    },

    // 选择客户名称：请求报价单
    *pleaseQun({ payload, callback }, { call }) {
      const response = yield call(pleaseListqun, payload);
      if (callback) {
        callback(response);
      }
    },

    // 根据报价单id获取产品等信息
    *crmquoGet({ payload, callback }, { call }) {
      const response = yield call(getEmpSeleInfo, payload);
      if (response.success) {
        callback(response);
      }
    },

    // 所属成本中心
    *costCenter({ payload, callback }, { call }) {
      const response = yield call(costCenterList, payload);
      if (response.success) {
        callback(response);
      }
    },

    // 获取缴费人员类别（参保身份)
    *personnelCategory({ payload, callback }, { call }) {
      const response = yield call(personnelStatusList, payload);
      if (response.success) {
        callback(response);
      }
    },

    // 根据执行地调出执行方
    *executiveParty({ payload, callback }, { call }) {
      const response = yield call(getPartyList, payload);
      if (response.success) {
        callback(response);
      }
    },

    // 根据执行地查询五险合不合一
    *combinationorOne({ payload, callback }, { call }) {
      const response = yield call(agreeWithone, payload);
      if (response.success) {
        callback(response);
      }
    },

    // 提交时的提示弹框
    *tipsalert({ payload, callback }, { call }) {
      const response = yield call(upTipsalert, payload);
      callback(response);
    },

    // 获取公积金比例下拉列表
    *providentRatio({ payload, callback }, { call }) {
      const response = yield call(providentRatioList, payload);
      if (response.success) {
        callback(response);
      }
    },

    //
    *providentFund({ payload, callback }, { call }) {
      const response = yield call(providentFundList, payload);
      if (response.success) {
        callback(response);
      }
    },

    // 根据公积金比例账户政策组合
    *policyMix({ payload, callback }, { call }) {
      const response = yield call(accountPolicy, payload);
      if (response.success) {
        callback(response);
      }
    },

    // 根据执行地查询服务配置
    *serviceConfiguration({ payload, callback }, { call }) {
      const response = yield call(serviceConfiguraList, payload);
      if (response.success) {
        callback(response);
      }
    },

    // 获取劳动合同信息
    *contractInformation({ payload, callback }, { call }) {
      const response = yield call(laborContract, payload);
      if (response.success) {
        callback(response);
      }
    },

    // 判断是否员工多派
    *submissionMessage({ payload, callback }, { call }) {
      const response = yield call(isStafffaction, payload);
      if (response.success) {
        callback(response);
      }
    },

    // 增员弹出提示框
    *alertTips({ payload, callback }, { call }) {
      const response = yield call(addAlert, payload);
      if (response.success) {
        callback(response);
      }
    },
    // 批量取消增员
    *batchCancelAddemp({ payload }, { call }) {
      const response = yield call(batchCancelAddemp, payload);
      return response;
    },
    // 模板产品列表
    *getPdInfoList({ payload }, { call }) {
      const response = yield call(getPdInfoList, payload);
      return response;
    },

    // 上传文件:批量进度
    uploadFileWithProgress: [
      function*({ payload }, { call, put }) {
        try {
          const response = yield call(uploadFileAddEmp, payload);
          if (response.success) {
            // 不是100表示需要走队列
            if (response.data && response.data.successProp !== 100) {
              const { batchId } = response.data;
              const batchTask = batchTaskFactory(batchId, namespace, 'handleBatchTask');

              yield put.resolve({
                type: `socket/${SocketActions.subSocketChannel}`,
                payload: {
                  batchTask,
                },
              });
              // 订阅成功后再触发进度条
              yield put({
                type: 'updateModelData',
                payload: { showProgress: true },
              });
            } else {
              yield put({
                type: 'handleBatchTask',
                payload: response.data,
              });
            }
          } else {
            message.warning(response.message || '上传文件错误：服务器端错误');
          }

          // 无需返回response对象
        } catch (e) {
          console.error(e);
        }
      },
      { type: 'throttle', ms: 10000 },
    ],
    *handleBatchTask({ payload }, { put, select }) {
      const state = yield select(s => s[namespace]);
      let { showProgress, resultInfo, currentStep } = state;

      const { batchQuery } = state;
      showProgress = true;
      if (payload.successProp >= 100) {
        resultInfo.errorParams = {
          batchId: payload.batchId,
          sendType: batchQuery.sendType,
          isSerSetFlag: batchQuery.isSerSetFlag,
          tempFlag: batchQuery.tempFlag,
          advancedSetFlag: batchQuery.advancedSetFlag,
          pdIds: batchQuery.pdIds,
          citySplitFlag: batchQuery.citySplitFlag,
          dateSplitFlag: batchQuery.dateSplitFlag,
        };
        resultInfo = { ...resultInfo, ...payload };
        currentStep += 1;
        showProgress = false;
        // 先更新进度
        yield put({
          type: 'updateBatchTask',
          payload: {
            progressPercent: payload.successProp,
            resultInfo,
          },
        });
        console.timeEnd('批量增员时间');
        yield delay(3000);
        // 再更新状态
        yield put({
          type: 'updateBatchTask',
          payload: {
            currentStep,
            showProgress,
          },
        });
      } else {
        yield put({
          type: 'updateBatchTask',
          payload: { progressPercent: payload.successProp, resultInfo },
        });
      }
    },
    // 获取所属客服列表
    *fetchRespUserList({ payload }, { call, put }) {
      const response = yield call(getRespUserList, payload);
      yield put({
        type: 'updateModelData',
        payload: {
          respUserList: [],
        },
      });
      if (response.success && response.data) {
        yield put({
          type: 'updateModelData',
          payload: {
            respUserList: Array.isArray(response.data) ? response.data : [],
          },
        });
      } else {
        message.warning(response.message || '获取所属客服数据：服务端错误');
      }
    },
  },

  reducers: {
    // 获取列表
    updateList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = data.pageRecords && Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        pageData: {
          list,
          pagination: { total: data.totalCount || 0, current: currentPage, pageSize },
        },
      };
    },
    // 更新批量上传参数
    updateQuery(state, { payload }) {
      return {
        ...state,
        batchQuery: { ...state.batchQuery, ...payload },
      };
    },
    // 更新选择报价单的参数
    updateQuoQuery(state, { payload }) {
      return {
        ...state,
        addempQuery: { ...state.addempQuery, ...payload },
      };
    },
    dictionList(state, { payload }) {
      return {
        ...state,
        dictionList: { ...payload },
      };
    },
    // 问题人员详情
    getProDetail(state, { payload }) {
      return {
        ...state,
        proBaseList: payload,
        proFbList: payload.probFdbkList,
        probId: payload.probId,
      };
    },
    // 设置修改当前state数据
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 设置页签状态
    updateTabListQuery(state, { payload }) {
      const { tabList } = state;
      tabList.forEach((item, index) => {
        if (item.itemCode === payload.activeKey) {
          tabList[index].isHasBadge = false;
        }
      });
      return {
        ...state,
        tabList,
        ...payload,
      };
    },
    // 更新批量任务数据
    updateBatchTask(state, { payload }) {
      // let { showProgress, resultInfo, currentStep } = state;

      // const { batchQuery } = state;
      // showProgress = true;
      // if (payload.successProp >= 100) {
      //   resultInfo.errorParams = {
      //     batchId: payload.batchId,
      //     sendType: batchQuery.sendType,
      //     isSerSetFlag: batchQuery.isSerSetFlag,
      //     tempFlag: batchQuery.tempFlag,
      //     advancedSetFlag: batchQuery.advancedSetFlag,
      //     pdIds: batchQuery.pdIds,
      //     citySplitFlag: batchQuery.citySplitFlag,
      //     dateSplitFlag: batchQuery.dateSplitFlag,
      //   };
      //   resultInfo = { ...resultInfo, ...payload };
      //   currentStep += 1;
      //   showProgress = false;
      // }
      return {
        ...state,
        ...payload,
      };
    },
  },
  subscriptions: {
    socket({ dispatch }) {
      service.listen(async action => {
        // 判断是否自己命名空间的回调

        if (action.namespace === namespace) {
          switch (action.type) {
            case 'task':
              await dispatch({
                type: 'handleBatchTask',
                payload: action.data,
              });
              await dispatch({
                type: `socket/${SocketActions.handleUpdateBatchTask}`,
                payload: {
                  successProp: action.data.successProp,
                  batchId: action.data.batchId,
                },
              });
              // 全局保存
              dispatch({
                type: 'publicdata/updateBatchTaskData',
                payload: action.data,
              });
              break;
          }
        }
      }, namespace);
    },
  },
};

export default ModelAddEmp;
